<template>
  <div>
    <div>
      <ul v-if="isUpdate" class="el-upload-list el-upload-list--picture-card">
        <li
          tabindex="0"
          class="el-upload-list__item is-ready"
          :style="'width: ' + width + 'px;height: ' + height + 'px'"
        >
          <div>
            <el-upload
              :accept="accept"
              class="avatar-uploader"
              :style="'width: ' + width + 'px;height: ' + height + 'px'"
              action="http://up-z1.qiniup.com/"
              :show-file-list="false"
              :http-request="uploadFile"
              :before-upload="beforeAvatarUpload"
            >
              <i class="el-icon-plus avatar-uploader-icon" :style="'width: ' + width + 'px;height: ' + height + 'px;line-height: '+ height + 'px'"></i>
            </el-upload>
          </div>
        </li>
      </ul>

      <ul
        v-for="(item, index) in value"
        :key="index"
        class="el-upload-list el-upload-list--picture-card"
      >
        <li
          tabindex="0"
          class="el-upload-list__item is-ready"
          :style="'width: ' + width + 'px;height: ' + height + 'px'"
        >
          <div>
            <img :src="item" alt="" class="el-upload-list__item-thumbnail" />
            <span class="el-upload-list__item-actions">
              <span
                class="el-upload-list__item-preview"
                @click="zoomMaterial(index)"
              >
                <i class="el-icon-view" />
              </span>
              <span
                v-if="isUpdate"
                class="el-upload-list__item-delete"
                @click="deleteMaterial(index)"
              >
                <i class="el-icon-delete" />
              </span>
            </span>
          </div>
        </li>
      </ul>

      <el-dialog append-to-body :visible.sync="dialogVisible" width="35%">
        <img :src="url" alt="" style="width: 100%" />
      </el-dialog>
    </div>

    <div slot="tip" class="el-upload__tip">
      只能上传{{ accept }}文件，且不超过{{ fileSize }}M
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { getUploadToken } from "@/api/system/oss";
export default {
  props: {
    // 是否可编辑
    isUpdate: {
      type: Boolean,
      default() {
        return true;
      },
    },
    // 图片数据
    value: {
      type: Array,
      default() {
        return [];
      },
    },
    accept: {
      type: String,
      default: ".jpg,.png",
    },
    disabled: Boolean,
    //限制个数
    limit: {
      type: Number,
      default: 5,
    },
    fileSize: {
      type: Number,
      default: 5,
    },
    // 宽度
    width: {
      type: Number,
      default() {
        return 150;
      },
    },
    // 宽度
    height: {
      type: Number,
      default() {
        return 150;
      },
    },
  },
  name: "AvatarUpload",
  data() {
    return {
      dialogVisible: false,
      url: "",
      token: "",
    };
  },
  created() {},
  methods: {
    zoomMaterial(index) {
      this.dialogVisible = true;
      this.url = this.value[index];
    },
    deleteMaterial(index) {
      const that = this;
      this.$confirm("是否确认删除？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(function () {
        that.value.splice(index, 1);
        that.urls = [];
      });
    },
    uploadToken() {
      return new Promise(function (resolve, reject) {
        getUploadToken().then((res) => {
          if (res.code == 200) {
            resolve(res.data);
          } else {
            reject();
            this.$message({
              message: "获取凭证出错！",
              type: "error",
              center: true,
            });
          }
        });
      });
    },
    uploadFile(raw) {
      if (this.limit == this.value.length) {
        this.$message({
          message: "最多上传" + this.limit + "张图片！",
          type: "error",
          center: true,
        });
        return false;
      }
      this.uploadToken().then((token) => {
        let formData = new FormData();
        formData.append("file", raw.file);
        formData.append("token", token.token);
        //获取后缀名
        let ext = raw.file.name.substr(raw.file.name.lastIndexOf(".") + 1);
        formData.append("key", token.fileName + "." + ext);
        let config = {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        };
        axios.post("http://up-z1.qiniup.com/", formData, config).then((res) => {
          if (res.status == 200) {
            var dataStr = res.data;
            dataStr = dataStr.substring(0, dataStr.length - 2);
            var dataObj = JSON.parse(dataStr);
            this.value.push(dataObj.fileUrl);
          } else {
            this.$message({
              message: "上传出错，请重试！",
              type: "error",
              center: true,
            });
          }
        });
      });
    },

    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < this.fileSize;

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 " + this.fileSize + "!");
      }
      return isLt2M;
    },
  },
};
</script>
<style>
.avatar-uploader .el-upload {
  border: none;
  /* border: 1px dashed #d9d9d9; 
    border-radius: 6px;*/
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border: none;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
.avatar {
  display: block;
}

.el-upload__tip {
  margin-top: -10px;
}
</style>
<style lang="scss" scoped>
.el-icon-circle-close {
  color: red;
}
.material-name {
  padding: 8px 0px;
}
.col-do {
  text-align: center;
}
.button-do {
  padding: unset !important;
  font-size: 12px;
}
</style>
